// pages/game/newplay.js
const app =getApp();
const TRADIS = require('../../tradis/tradis.js');
import config from '../../utils/config.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageIn: 'detail',
    go: false,
    board_id:'',
    borderindex:0,
    borderlist:[],
    isstar: false,
    board: {},
    topic: {},
    rightanswer: {},
    tips: '',
    score: {},
    isFetch: true,
    answer: [],
    defaultarr: [],
    ciwords: [],
    defaultwords: [],
    gotimer: null,
    gotime: 3,
    showplus: false,
    money: false,
    music: {},
    music_321: {},
    music_background:'',
    music_bingo: '',
    music_click: '',
    music_error: '',
    music_over: '',
    music_readygo: '',
    showAns:false,
    iswrong:false,
    lifeTime:0,
    lifeTimer:null,
    bgmusIsPlay:false,
    isWin: false,
    winObj: {},
    ckindex:0,
  
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu({});
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    TRADIS.tradis(this);
    if (this.data.isstar == false) {
      let token = wx.getStorageSync('token');
      if (token) {
        this.gameStart();
        this.setData({
          userInfo: wx.getStorageSync('userInfo'),
        })

      } else {
        wx.navigateTo({
          url: '/pages/auth/getuserinfo',
        })
      }
    }
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(this.data.lifeTimer);
    clearInterval(this.data.gotimer);
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  gameStart: function () {
    wx.request({
      url: app.globalData.api + '/board/start.html&token=' + wx.getStorageSync('token'),
      method: 'get',
      success: (res) => {
        if (res.data.code == 0) {
          this.setData({
            board_id: res.data.data.board_id,
            borderlist: res.data.data.list,
            isstar: true,
          })
          this.data.jumptime = setTimeout(() => {
            this.setData({
              showjump: true,
            });
          }, 5 * 1000);
          this.getMusic();


        }
        else {
          app.fetchError(res.data.code, res.data.msg);
        }
      }
    })
  },
  /**
 * 加载音频资源文件
 */
  getMusic: function () {

    this.data.music_321 = wx.createInnerAudioContext()
    this.data.music_321.autoplay = false;
    this.data.music_321.src = '/music/music_321.mp3';

    this.data.music_readygo = wx.createInnerAudioContext();
    this.data.music_readygo.autoplay = false;
    this.data.music_readygo.src = '/music/music_readygo.mp3';

    this.data.music_bingo = wx.createInnerAudioContext();
    this.data.music_bingo.autoplay = false;
    this.data.music_bingo.src = '/music/music_bingo.mp3';

    this.data.music_error = wx.createInnerAudioContext();
    this.data.music_error.autoplay = false;
    this.data.music_error.src = '/music/music_error.mp3';

    this.data.music_click = wx.createInnerAudioContext();
    this.data.music_click.autoplay = false;
    this.data.music_click.src = '/music/music_click.mp3';

    this.data.music_over = wx.createInnerAudioContext();
    this.data.music_over.autoplay = false;
    this.data.music_over.src = '/music/music_over.mp3';

    this.data.music_background = wx.createInnerAudioContext();
    this.data.music_background.autoplay = false;
    this.data.music_background.src = '/music/music_background.mp3';

    this.data.music_321.onCanplay(() => {
      this.data.music_321.play();
      this.data.music_321.offCanplay();
      this.data.gotimer = setInterval(() => {

        // console.log(this.data.gotime);
        if (this.data.gotime <= 0) {

          clearInterval(this.data.gotimer);
          this.setData({
            go: true
          })
          //开始题目
        //  this.Interval(this.data.borderlist[this.data.borderindex].times);
          this.fetchStart();
        }

        else {
          if (this.data.gotime == 1) {
            this.data.music_readygo.play();
            setTimeout(()=>{
              this.data.music_background.play();
              this.setData({
                bgmusIsPlay:true,
              })
            },3000)
          }
          this.data.gotime--;
          this.setData({
            gotime: this.data.gotime
          })
        }


      }, 1000);
    });
  },
  Stop_music:function(){
    this.data.music_background.stop();
    this.setData({
      bgmusIsPlay: false,
    })
  },
  Play_music:function(){
    this.data.music_background.play();
    this.setData({
      bgmusIsPlay: true,
    })
  },
  fetchStart: function () {
    var detail = this.data.borderlist[this.data.borderindex];
    var ciwords = [];
    for (var i = 0; i < detail.options.length; i++) {
      var o = { "isactive": false, "word": detail.options[i] };
      ciwords.push(o);
    }
    var asw = [];
    for (var i = 0; i < detail.title.length; i++) {
      if (detail.title[i]=='?'){
        var o = { 'word': '?', 'index': i, 'disable': false };
      }
      else{
        var o = { 'word': detail.title[i], 'index': i, 'disable': true };
      }
      asw.push(o);
    }
    this.setData({
      ciwords: ciwords,
      answer: asw,
      nowindex: 0,
    });
  },
  setAnswer: function(e){
    this.data.music_click.stop();
    this.data.music_click.play();
    wx.vibrateShort();
    this.setData({
      ckindex: e.currentTarget.dataset.index,
      showAns: true,
    })
    if (e.currentTarget.dataset.index == this.data.borderlist[this.data.borderindex].index){
      console.log('正确');
      if (this.data.borderindex >= (this.data.borderlist.length - 1)) {
        this.data.music_background.stop();
        this.data.music_over.play();
        clearInterval(this.data.lifeTimer);
        setTimeout(() => {
          this.setData({
            showAns: false,
          })
          this.gameEnd(1, this.data.borderlist[this.data.borderindex].id);
        }, 500)
      
      }
      else{
        clearInterval(this.data.lifeTimer);
        this.Interval(this.data.borderlist[this.data.borderindex+1].times);
        setTimeout(()=>{
          this.setData({
            showAns: false,
          })
          this.continue_fn();
        },500)
      }

    }
    else{
      this.data.music_background.stop();
      this.setData({
        bgmusIsPlay: false,
      });
      this.data.music_error.play();
      console.log('错误');
      clearInterval(this.data.lifeTimer);
      this.gameEnd(0, this.data.borderlist[this.data.borderindex].id);
      setTimeout(() => {
        this.setData({
          error: false,
          showAns: true,
          iswrong: true,
        });
      },1000);

    }
  },
  /*游戏结束*/
  gameEnd: function (status, id) {
    wx.request({
      url: app.globalData.api + '/board/end.html&token=' + wx.getStorageSync('token'),
      method: 'post',
      data: {
        "board_id": this.data.board_id,
        "is_complete": status,
        "question_id": id,
      },
      success: (res) => {
        console.log(res);
        if (status == 1) {
          var winObj = {
            id: res.data.data.bonus.id,
            fee: res.data.data.bonus.fee,
            type: res.data.data.bonus.type,
            grade: JSON.stringify(res.data.data.grade),
          }
          // this.setData({
          //   isWin: true,
          //   winObj: winObj
          // })
          console.log('/pages/hongbao/detail?id=' + res.data.data.bonus.id + '&fee=' + res.data.data.bonus.fee + "&type=" + res.data.data.bonus.type + '&grade=' + JSON.stringify(res.data.data.grade));
          wx.redirectTo({
            url: '/pages/hongbao/detail?id=' + res.data.data.bonus.id + '&fee=' + res.data.data.bonus.fee + "&type=" + res.data.data.bonus.type + '&grade=' + JSON.stringify(res.data.data.grade),
          })
        }

      }
    })
  },
  openHB: function () {
    this.setData({
      isfz: true,
    })
    setTimeout(() => {
      this.setData({
        isfz: false,
      })
      wx.redirectTo({
        url: '/pages/hongbao/detail?fee=' + this.data.winObj.fee + '&bonus_id=' + this.data.winObj.id,
      })
    }, 1500)
  },
  closeHB: function () {
    this.setData({
      isWin: false,
      winObj: {}
    })
    wx.redirectTo({
      url: '/pages/index/index',
    })
  },
  /**
 * 游戏进行中，继续
 */
  continue_fn: function () {
    var index = this.data.borderindex + 1;
    this.setData({
      istip: false,
      borderindex: index,
    })
    this.fetchStart();

  },
  /**
* 游戏结束，再来一起
*/
  again_fn: function () {
    wx.redirectTo({
      url: '/pages/index/index?from_detail=1',
    })
    // this.setData({
    //   istip: false,
    //   iswrong:false,
    //   go: false,
    //   board_id: '',
    //   borderindex: 0,
    // })
    // this.gameStart();
  },
  Interval:function(time){
    this.setData({
      lifeTime:time*10,
    });
    this.data.lifeTimer=setInterval(()=>{
      if (this.data.lifeTime>0){
        this.data.lifeTime--;
        this.setData({
          lifeTime: this.data.lifeTime,
        })
      }
      else{
        clearInterval(this.data.lifeTimer);
        console.log('错误');
        this.data.music_background.stop();
        this.setData({
          bgmusIsPlay: false,
        });
        this.data.music_error.play();
        this.gameEnd(0, this.data.borderlist[this.data.borderindex].id);
        this.setData({
          error: false,
          showAns: true,
          iswrong: true,
        });

      }
    },100)
  },
})